import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

String baseUrl = "";
ResponseType responseType = ResponseType.json;
int receiveTimeout = 3600;
int sendTimeout = 3600;
int connectTimeout = 3600;

Future<String> getLocalhost() async{
  var interfaces = await NetworkInterface.list();
  NetworkInterface inter = interfaces[0];
  InternetAddress? interAddress;
  // 找到ipv4地址
  for (var address in inter.addresses) {
    if (address.type == InternetAddressType.IPv4) {
      interAddress = address;
      break;
    }
  }
  String localHost = interAddress!.address.toString();
  return localHost;
}

class DioManager {
  final Dio? _dio;
  BaseOptions? options;

  static DioManager? _instance;

  DioManager._(this._dio);

  factory DioManager() {
    if (_instance == null) {
      _instance = DioManager._(Dio());
      _instance?._dio?.options = BaseOptions(
        baseUrl: baseUrl,
        responseType: responseType,
        receiveTimeout: Duration(seconds: receiveTimeout),
        sendTimeout: Duration(seconds: sendTimeout),
        connectTimeout: Duration(seconds: connectTimeout),
      );
      _instance?._dio?.interceptors.add(PrintInterceptor());
    }
    return _instance!;
  }

  void addInterceptor(Interceptor interceptor) {
    _dio?.interceptors.add(interceptor);
  }

  void removeInterceptor(Interceptor interceptor) {
    _dio?.interceptors.remove(interceptor);
  }

  /// 清除
  void clear() {
    _dio?.close();
    _instance = null;
  }

  Future<dynamic> get({
    required String path,
    Options? options,
    dynamic queryParameters,
    dynamic data,
    Function(int, int)? onReceiveProgress,
  }) async {
    Response response;
    try {
      response = await _dio!.get(
        path,
        data: data,
        queryParameters: queryParameters,
        options: options,
        onReceiveProgress: (count, total) => onReceiveProgress,
      );
      return response;
    } on DioException catch (e) {
      return e.response;
    } on Exception catch (e) {
      return e;
    } on Error catch (error) {
      return error;
    }
  }

  Future<dynamic> post({
    required String path,
    Options? options,
    dynamic data,
    Function(int)? progress,
    Function(int count, int total)? onSendProgress,
    Function(int count, int total)? onReceiveProgress,
  }) async {
    try {
      Response response = await _dio!.post(
        path,
        data: data,
        options: options,
        onSendProgress: (count, total) => onSendProgress,
        onReceiveProgress: (count, total) => onReceiveProgress,
      );
      return response;
    } on DioException catch (dioError) {
      return dioError.response;
    } on Exception catch (error) {
      return error;
    } on Error catch (error) {
      return error;
    }
  }

  Future<dynamic> postFile({
    required String path,
    Options? options,
    dynamic data,
    Function(int)? progress,
    Function(int count, int total)? onSendProgress,
    Function(int count, int total)? onReceiveProgress,
  }) async {
    try {
      FormData formData = FormData.fromMap(data);
      Response response = await _dio!.post(
        path,
        data: formData,
        options: options,
        onSendProgress: (count, total) => onSendProgress,
        onReceiveProgress: (count, total) => onReceiveProgress,
      );
      return response;
    } on DioException catch (dioError) {
      return dioError.response;
    } on Error catch (error) {
      return error;
    }
  }
}

class PrintInterceptor extends InterceptorsWrapper {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (kDebugMode) {
      printRed('''打印拦截器 请求地址：${options.uri} \n 方法：${options.method} \n 头部：${options.headers} \n 参数：${options.data}''');
    }
    return handler.next(options);
  }

  @override
  void onResponse(Response<dynamic> response, ResponseInterceptorHandler handler) {
    if (kDebugMode) {
      printRed('''打印拦截器 响应数据：状态Code：${response.statusCode}  状态数据：${response.statusMessage} \n 头部 ${response.headers} \n 数据：${response.data}''');
    }
    return handler.next(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (kDebugMode) {
      printRed('''打印拦截器 异常数据：$err''');
    }
    // Response? response = err.response;
    // if (response != null && response.statusCode == 401) {
    //   // 跳转到登录页面
    //   BuildContext? buildContext = NavigatorProvider.navigatorKey.currentContext;
    //   if (buildContext != null) {
    //     NavigatorProvider.navigatorKey.currentState?.pushNamedAndRemoveUntil("/login", (route) => false);
    //     return;
    //   }
    // }埃及金字塔
    return handler.next(err);
  }
}

printRed(dynamic msg) {
  if (kDebugMode) {
    print("\x1B[31m ${msg} \x1B[0m");
  }
}
